//
//  TBCircularSlider.m
//  JMControl
//
//  Created by Zhuangyh on 16/1/7.
//  Copyright © 2016年 dooya. All rights reserved.
//

#import "JMCircularSlider.h"
#import <CoreGraphics/CGContext.h>
#import <UIKit/UIKit.h>
#define ToRad(deg) 		( (M_PI * (deg)) / 180.0 )
//平方
#define SQR(x)			( (x) * (x) )
//
#define ToDeg(rad)		( (180.0 * (rad)) / M_PI )

@interface JMCircularSlider()
@property(nonatomic,strong)UITextField *textField;
@end

@implementation JMCircularSlider

#define TB_LINE_WIDTH 20
- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        _angle = 270;
        _textField = [[UITextField alloc] initWithFrame:CGRectMake(0, 0, 40, 40)];
        _textField.center = CGPointMake(frame.size.width/2, frame.size.height/2);
        [self addSubview:_textField];
    }
    return self;
}


- (void)drawRect:(CGRect)rect {
    [super drawRect:rect];
    NSLog(@"%s",__FUNCTION__);
    
    // Drawing code
    
    //一.画圆圈背景
    CGFloat radius = 80;
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    //Add the arc path
    CGContextAddArc(ctx, self.frame.size.width/2, self.frame.size.height/2, radius, 0, M_PI *2, 0);
    
    //Set the stroke colour
    [[UIColor grayColor]setStroke];
    
    //set Line width and cap
    CGContextSetLineWidth(ctx, TB_LINE_WIDTH);
    CGContextSetLineCap(ctx, kCGLineCapButt);
    
    //draw it!
    CGContextDrawPath(ctx, kCGPathStroke);
    
    
    //二.掩码图
    //创建一个基于位图的上下文（context）,并将其设置为当前上下文(context)
    UIGraphicsBeginImageContext(self.frame.size);
    CGContextRef imageCtx = UIGraphicsGetCurrentContext();
    
    CGContextAddArc(imageCtx, self.frame.size.width/2  , self.frame.size.height/2, radius, 0, ToRad(self.angle), 0);
    [[UIColor redColor]set];
    
    //Use shadow to create the Blur effect
    CGContextSetShadowWithColor(imageCtx, CGSizeMake(0, 0), self.angle/20, [UIColor blackColor].CGColor);
    
    //define the path
    CGContextSetLineWidth(imageCtx, TB_LINE_WIDTH);
    CGContextDrawPath(imageCtx, kCGPathStroke);
    
    //save the context content into the image mask
    CGImageRef mask = CGBitmapContextCreateImage(UIGraphicsGetCurrentContext());
    
    UIGraphicsEndImageContext();
    
    
    //对上下文进行裁剪
    /** Clip Context to the mask **/
    CGContextSaveGState(ctx);
    
    CGContextClipToMask(ctx, self.bounds, mask);
    CGImageRelease(mask);
    
//    //用来看mask的样子   需要注释的
//    CGContextDrawImage(ctx, self.bounds, mask);
    
    //三.绘制渐变效果
//    定义颜色的变化范围
//    定义渐变的方向
//    选择颜色空间
//    创建并绘制渐变
    //Define the colour steps
    CGFloat components[8] = {
        0.0, 0.0, 1.0, 1.0,     // Start color - Blue
        1.0, 0.0, 1.0, 1.0 };   // End color - Violet
    
    CGColorSpaceRef baseSpace = CGColorSpaceCreateDeviceRGB();
    CGGradientRef gradient = CGGradientCreateWithColorComponents(baseSpace, components, NULL, 2);
    
    //Define the gradient direction
    CGPoint startPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMinY(rect));
    CGPoint endPoint = CGPointMake(CGRectGetMidX(rect), CGRectGetMaxY(rect));
    
    //Choose a colour space
    CGColorSpaceRelease(baseSpace), baseSpace = NULL;
    
    //Create and Draw the gradient
    CGContextDrawLinearGradient(ctx, gradient, startPoint, endPoint, 0);
    CGGradientRelease(gradient), gradient = NULL;
    
    //
    CGContextRestoreGState(ctx);
    
//    //四绘制手柄 只绘制了一半？
    [self drawTheHandle:ctx];
}

#pragma mark - 绘制手柄
-(CGPoint)pointFromAngle:(int)angleInt{
    //半径
    CGFloat radius = 80;
    
    //Define the Circle center
    CGPoint centerPoint = CGPointMake(self.frame.size.width/2 - TB_LINE_WIDTH/2, self.frame.size.height/2 - TB_LINE_WIDTH/2);
    
    //Define The point position on the circumference
    CGPoint result;
    result.y = round(centerPoint.y + radius * sin(ToRad(-angleInt))) ;
    result.x = round(centerPoint.x + radius * cos(ToRad(-angleInt)));
    
    return result;
}

-(void) drawTheHandle:(CGContextRef)ctx{
    
    CGContextSaveGState(ctx);
    
    //I Love shadows
    CGContextSetShadowWithColor(ctx, CGSizeMake(0, 0), 3, [UIColor blackColor].CGColor);
    
    //Get the handle position!
    CGPoint handleCenter =  [self pointFromAngle: self.angle];
    
    //Draw It!
    [[UIColor colorWithWhite:1.0 alpha:0.7]set];
    CGContextFillEllipseInRect(ctx, CGRectMake(handleCenter.x, handleCenter.y, TB_LINE_WIDTH, TB_LINE_WIDTH));
    
    CGContextRestoreGState(ctx);
}

#pragma mark -用户跟踪
-(BOOL)beginTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    NSLog(@"%s",__FUNCTION__);
    [super beginTrackingWithTouch:touch withEvent:event];
    
    return YES;//需要跟踪用户的dragging，所以返回YES
}

-(BOOL)continueTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    NSLog(@"%s",__FUNCTION__);
    [super continueTrackingWithTouch:touch withEvent:event];
    
    //Get touch location
    CGPoint lastPoint = [touch locationInView:self];
    
    //Use the location to design the Handle
    [self movehandle:lastPoint];
    
    //We'll see this function in the next section:
    [self sendActionsForControlEvents:UIControlEventValueChanged];
    
    return YES;
}

-(void)movehandle:(CGPoint)lastPoint{
    
    //Get the center
    CGPoint centerPoint = CGPointMake(self.frame.size.width/2,
                                      self.frame.size.height/2);
    
    //Calculate the direction from the center point to an arbitrary position.
    float currentAngle = AngleFromNorth(centerPoint,
                                        lastPoint,
                                        NO);
    int angleInt = floor(currentAngle);
    
    //Store the new angle
    self.angle = 360 - angleInt;
    
    //Update the textfield
    _textField.text =  [NSString stringWithFormat:@"%d",
                        self.angle];
    
    //Redraw
    [self setNeedsDisplay];
}

static inline float AngleFromNorth(CGPoint p1, CGPoint p2, BOOL flipped) {
    CGPoint v = CGPointMake(p2.x-p1.x,p2.y-p1.y);
    float vmag = sqrt(SQR(v.x) + SQR(v.y)), result = 0;
    v.x /= vmag;
    v.y /= vmag;
    double radians = atan2(v.y,v.x);
    result = ToDeg(radians);
    return (result >=0  ? result : result + 360.0);
}

-(void)endTrackingWithTouch:(UITouch *)touch withEvent:(UIEvent *)event{
    NSLog(@"%s",__FUNCTION__);
    [super endTrackingWithTouch:touch withEvent:event];
}

@end
